<template>
<view class="imgBox">
  <image
    v-if="src"
    class="cdn"
    :mode="mode"
    :lazyLoad="lazyLoad"
    :showMenuByLongpress="showMenuByLongpress"
    :src="cdnUrl"
  />
  <view v-else class="placeholder"></view>
</view>
</template>

<script setup>
import { ref, watch, inject, onBeforeMount } from "vue";

const props = defineProps({
  src: {
    type: [String],
    default: "",
  },
  mode: {
    type: String,
    default: "scaleToFill",
  },
  lazyLoad: {
    type: Boolean,
    default: false,
  },
  showMenuByLongpress: {
    type: Boolean,
    default: false,
  }
});
const cdnUrl = ref("");
const cdn = inject("cdn");
async function getCdnUrl (newVal) {
  if (newVal.includes("http")) {
    cdnUrl.value = newVal;
  } else if (process.env.NODE_ENV === "development") {
    const img = await import("@/utils/img");
    cdnUrl.value = img.default[newVal];
  } else {
    // 拿到全局注入的cdn地址 拼接起来
    cdnUrl.value = cdn + newVal;
  }
}
onBeforeMount(() => {
  if (props.src) getCdnUrl(props.src);
});
watch(
  () => props.src,
  (src) => {
    getCdnUrl(src);
  }
);
</script>

<style lang="scss">
.imgBox{
  display: inline-block;
  overflow: hidden;
  .cdn,
  .placeholder {
    display: block;
    width: 100%;
    height: 100%;
  }
  .placeholder {
    background-color: #ccc;
  }
}
</style>
